package cn.edu.nit.sys.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.jsonwebtoken.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class JwtUtils {

    private static final Long APP_EXPIRE = 7 * 24 * 60 * 60 * 1000L;    // 有效期 7天
    private static final Long WEB_EXPIRE = 30 * 60 * 1000L;     // 有效期30分钟
    private static final String SECRET = "school";  // 秘钥


    /**
     * 生成Token
     * @param username
     * @return
     */
    public static String generateToken(String username, String os) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + WEB_EXPIRE);
        if("app".equals(os)) {
            expireDate = new Date(nowDate.getTime() + APP_EXPIRE);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        return Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setClaims(map)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * token 是否过期
     * @param claims
     * @return
     */
    public static boolean isExpire(Claims claims) {
        return ObjectUtils.isEmpty(claims) ||claims.getExpiration().before(new Date());
    }

    /**
     * 解析token获取用户名
     * @param request
     * @return
     */
    public static Map<String, Object> getInfoFromToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String, Object> map = new HashMap<>();
        if(ObjectUtils.isEmpty(token)) {
            return map;
        }
        try {
            Jws<Claims> jws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
            Claims body = jws.getBody();
            Object username = body.get("username");
            Object authorityList = body.get("authorities");
            map.put("username", username);
            map.put("authorities", authorityList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
